#include "ssl_util.h"

namespace qio {

SSLHelper::~SSLHelper() {}  // NOLINT

SSLConfig::SSLConfig(const std::string &cert_file,
                     const std::string &priv_file) noexcept
    :  // NOLINT
      SSLHelper(),
      cert_file_(cert_file),
      priv_file_(priv_file),
      ssl_ctx_(nullptr) {
  Build();
}

void SSLConfig::Build() QIO_NOEXCEPT {
  // todo add log,通知用户 SSL 信息加载失败
  // tip: SSL_CTX_XXX API 返回 1 代表操作成功
  ssl_ctx_ = SSL_CTX_new(SSLv23_method());
  SSL_CTX_set_options(ssl_ctx_, SSL_OP_NO_SSLv3);
  int r = SSL_CTX_use_certificate_file(ssl_ctx_, cert_file_.c_str(),
                                       SSL_FILETYPE_PEM);
  if (r != 1) {
    goto fail_case;
  }
  r = SSL_CTX_use_PrivateKey_file(ssl_ctx_, priv_file_.c_str(),
                                  SSL_FILETYPE_PEM);
  if (r != 1) {
    goto fail_case;
  }
  r = SSL_CTX_check_private_key(ssl_ctx_);
  if (r == 1) {
    return;
  }
fail_case:
  SSL_CTX_free(ssl_ctx_);
  ssl_ctx_ = nullptr;
}

SSL_CTX *SSLConfig::GetSSLContext() const QIO_NOEXCEPT { return ssl_ctx_; }

SSLConfig::~SSLConfig() noexcept {
  if (ssl_ctx_) {
    SSL_CTX_free(ssl_ctx_);
  }
}

}  // namespace qio
